package cn.time1024.time_app.ui.notifications

import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.fragment.app.Fragment
import androidx.navigation.fragment.findNavController
import com.example.timeassistant.network.TokenManager
import cn.jpush.android.api.JPushInterface
import cn.time1024.time_app.LoginActivity
import cn.time1024.time_app.databinding.FragmentNotificationsBinding

class NotificationsFragment : Fragment() {

    private var _binding: FragmentNotificationsBinding? = null
    private val binding get() = _binding!!

    /**
     * 创建“我的”页面的视图，绑定退出登录与“通知”入口点击事件。
     */
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        _binding = FragmentNotificationsBinding.inflate(inflater, container, false)
        val root: View = binding.root

        // 退出登录：清理本地 token 与保存的密码，并跳转登录页
        binding.btnLogout.setOnClickListener {
            val prefs = requireContext().getSharedPreferences("auth_prefs", android.content.Context.MODE_PRIVATE)
            prefs.edit()
                .remove("auth_token")
                .remove("saved_password")
                .apply()
            TokenManager.token = null

            Toast.makeText(requireContext(), "已退出登录", Toast.LENGTH_SHORT).show()
            startActivity(Intent(requireContext(), LoginActivity::class.java))
            requireActivity().finish()
        }

        // 通知入口：进入通知中心页面
        binding.rowNotifications.setOnClickListener {
            findNavController().navigate(cn.time1024.time_app.R.id.navigation_notification_center)
        }

        return root
    }

    /**
     * Fragment 可见时刷新用户信息与 RegistrationID 展示。
     */
    override fun onResume() {
        super.onResume()
        val prefs = requireContext().getSharedPreferences("TimeAssistant", android.content.Context.MODE_PRIVATE)
        val username = prefs.getString("username", "")
        val userId = prefs.getString("userId", "")
        val welcome = "欢迎您，$username (ID: $userId)"
        val rid = JPushInterface.getRegistrationID(requireContext())
        val ridText = if (rid.isNullOrEmpty()) "暂未获取" else rid
        binding.tvUserInfo.text = welcome
        binding.tvRegId.text = "RegistrationID: $ridText"
    }

    /**
     * 销毁视图绑定，避免内存泄漏。
     */
    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }
}